/**
 * 收藏夹导入
 * @type {exports}
 */
var dbUtils = require('./database.dao.utils');
var encry = require('./encryption.utils');
var _ = require('underscore');
var fs = require('fs');

//The starting time of windows system clock
var ms = new Date(1601, 0, 1).getTime();

function typeOfValue(value) {
  return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}


function numToDoubleChar(num) {
  return num < 10 ? '0' + num : num + '';
}

function dateFormat(date) {
  if (typeOfValue(date) === 'date') {
    return date.getFullYear() + numToDoubleChar(date.getMonth() + 1) + numToDoubleChar(date.getDate()) + numToDoubleChar(date.getHours()) + numToDoubleChar(date.getMinutes()) + numToDoubleChar(date.getSeconds());
  }
  return '';
}

function resolveTimestampToDateStr(timestamp) {
  if (/^\d+$/.test(timestamp)) {
    return dateFormat(new Date(ms + Math.floor(timestamp / 1000)));
  }
  return '';
}

function rebuildJsonToCommonJson(json, tag) {
  if (typeOfValue(json) === 'object' || typeOfValue(json) === 'array') {
    if ('name' in json && 'type' in json) {
      if (json['type'] === 'url') {
        return {
          url: json['url'] || '',
          type: 'url',
          tag: (tag || []).slice(0),
          name: json['name'] || '',
          time: resolveTimestampToDateStr(json['date_added'])
        };
      } else if (json['type'] === 'folder') {
        tag = (tag || []);
        tag.push(json['name'] || '');
        return {
          type: 'folder',
          name: json['name'] || '',
          time: resolveTimestampToDateStr(json['date_added']),
          child: rebuildJsonToCommonJson(json['children'], tag)
        };
      }
    }
    var result = [], key, tmp;
    for (key in json) {
      tmp = rebuildJsonToCommonJson(json[key], tag);
      tmp ? result.push(tmp) : '';
    }
    tag.pop();
    return result;
  }
}

function transferTreeToArray(jsonTree) {
  var jsonArr = [];
  if (typeOfValue(jsonTree) === 'array') {
    jsonTree.forEach(function (el) {
      Array.prototype.push.apply(jsonArr, transferTreeToArray(el));
    });
  } else if (typeOfValue(jsonTree) === 'object') {
    jsonArr.push(jsonTree);
    jsonTree['child'] ? Array.prototype.push.apply(jsonArr, transferTreeToArray(jsonTree['child'])) : '';
  }
  return jsonArr;
}

function sortByTime(jsonArr) {
  typeOfValue(jsonArr) === 'array' && jsonArr.sort(function (a, b) {
    return (a.time - b.time) * -1;
  });
}

function deleteType(jsonArr) {
  typeOfValue(jsonArr) === 'array' && jsonArr.forEach(function (el) {
    delete el.type;
  });
}

function attachExtraAttr(jsonArr, idFrom, orderFrom) {
  typeOfValue(jsonArr) === 'array' && jsonArr.forEach(function (el) {
    el['id'] = ++idFrom;
  });
}

function doImport(userid, data, callback) {
  var jsonTree = rebuildJsonToCommonJson(JSON.parse(data).roots.bookmark_bar.children, []);
  var jsonArr = transferTreeToArray(jsonTree);
  sortByTime(jsonArr);
  attachExtraAttr(jsonArr, 0, 0);
  jsonArr = _.where(jsonArr, {type: 'url'});
  deleteType(jsonArr);
  _.each(jsonArr, function (e) {
    console.log(e);
  });
  dbUtils.insert({
    user: 'wuqinglong',
    pass: encry.md5('wuqinglong'),
    time: dateFormat(new Date()),
    bookmarks: jsonArr
  }, function (err) {
    if (err) {
      console.log(err);
    } else {
      dbUtils.find(function (err, data) {
        if (err) {
          console.log(err);
        } else {
          console.log(data);
        }
      });
    }
  });
}


module.exports = function (path, userid, callback) {
  fs.exists(path, function (exists) {
    !exists ? callback('path not exists') : fs.readFile(path, 'utf-8', function (err, data) {
      err ? callback(err) : doImport(userid, data, callback);
    });
  });
};
